<template>
  <canvas ref="canvas" class="canvas-bg"></canvas>
</template>

<script>
export default {
  name: 'CanvasBg2',
  data() {
    return {
      ctx: null,
      colorOffset: null,
      mouse: {},
      config: {
        friction: 0.5,
        trails: 20,
        size: 50,
        dampening: 0.4,
        tension: 0.98
      },
      tentacles: [],
      animationId: null,
      isRunning: false,
      hasFirstInteraction: false
    };
  },
  mounted() {
    this.initCanvas();
  },
  beforeUnmount() {
    this.stopAnimation();
    this.removeEventListeners();
  },
  methods: {
    initCanvas() {
      Math.TWO_PI = Math.PI * 2;
      
      this.ctx = this.$refs.canvas.getContext("2d");
      this.isRunning = true;
      
      // 初始化颜色振荡器
      this.colorOffset = this.createColorOscillator({
        phase: Math.random() * Math.TWO_PI,
        amplitude: 85,
        frequency: 0.0015,
        offset: 285
      });
      
      // 初始化鼠标位置
      this.mouse = {
        x: window.innerWidth / 2,
        y: window.innerHeight / 2
      };
      
      this.setupEventListeners();
      this.resizeCanvas();
    },
    
    // 创建颜色振荡器
    createColorOscillator(options) {
      let value = 0;
      const oscillator = {
        phase: options.phase || 0,
        offset: options.offset || 0,
        frequency: options.frequency || 0.001,
        amplitude: options.amplitude || 1,
        update() {
          this.phase += this.frequency;
          value = this.offset + Math.sin(this.phase) * this.amplitude;
          return value;
        },
        value() {
          return value;
        }
      };
      return oscillator;
    },
    
    // 创建触手
    createTentacle(options) {
      const vm = this;
      
      function Node() {
        this.x = 0;
        this.y = 0;
        this.vy = 0;
        this.vx = 0;
      }
      
      const tentacle = {
        spring: options.spring + (Math.random() * 0.1) - 0.05,
        friction: vm.config.friction + (Math.random() * 0.01) - 0.005,
        nodes: [],
        
        init() {
          this.nodes = [];
          for (let i = 0; i < vm.config.size; i++) {
            const node = new Node();
            node.x = vm.mouse.x;
            node.y = vm.mouse.y;
            this.nodes.push(node);
          }
        },
        
        update() {
          let spring = this.spring;
          let node = this.nodes[0];
          
          node.vx += (vm.mouse.x - node.x) * spring;
          node.vy += (vm.mouse.y - node.y) * spring;
          
          for (let prev, i = 0, len = this.nodes.length; i < len; i++) {
            node = this.nodes[i];
            if (i > 0) {
              prev = this.nodes[i - 1];
              node.vx += (prev.x - node.x) * spring;
              node.vy += (prev.y - node.y) * spring;
              node.vx += prev.vx * vm.config.dampening;
              node.vy += prev.vy * vm.config.dampening;
            }
            node.vx *= this.friction;
            node.vy *= this.friction;
            node.x += node.vx;
            node.y += node.vy;
            spring *= vm.config.tension;
          }
        },
        
        draw() {
          let x = this.nodes[0].x;
          let y = this.nodes[0].y;
          let a, b;
          let i, len;
          
          vm.ctx.beginPath();
          vm.ctx.moveTo(x, y);
          
          for (i = 1, len = this.nodes.length - 2; i < len; i++) {
            a = this.nodes[i];
            b = this.nodes[i + 1];
            x = (a.x + b.x) * 0.5;
            y = (a.y + b.y) * 0.5;
            vm.ctx.quadraticCurveTo(a.x, a.y, x, y);
          }
          
          a = this.nodes[i];
          b = this.nodes[i + 1];
          vm.ctx.quadraticCurveTo(a.x, a.y, b.x, b.y);
          vm.ctx.stroke();
          vm.ctx.closePath();
        }
      };
      
      tentacle.init();
      return tentacle;
    },
    
    // 设置触手
    setupTentacles() {
      this.tentacles = [];
      for (let i = 0; i < this.config.trails; i++) {
        this.tentacles.push(this.createTentacle({
          spring: 0.45 + 0.025 * (i / this.config.trails)
        }));
      }
    },
    
    // 动画循环
    animate() {
      if (!this.isRunning) {
        return;
      }
      
      this.ctx.globalCompositeOperation = "source-over";
      this.ctx.fillStyle = "rgba(8,5,16,0.2)";
      this.ctx.fillRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
      this.ctx.globalCompositeOperation = "lighter";
      this.ctx.strokeStyle = "hsla(" + Math.round(this.colorOffset.update()) + ",90%,10%,0.1)";
      this.ctx.lineWidth = 1;
      
      for (let i = 0, tentacle; i < this.config.trails; i++) {
        tentacle = this.tentacles[i];
        tentacle.update();
        tentacle.draw();
      }
      
      this.animationId = requestAnimationFrame(() => this.animate());
    },
    
    // 调整canvas大小
    resizeCanvas() {
      this.ctx.canvas.width = window.innerWidth;
      this.ctx.canvas.height = window.innerHeight;
    },
    
    // 启动动画
    startAnimation() {
      if (!this.isRunning) {
        this.isRunning = true;
        this.animate();
      }
    },
    
    // 停止动画
    stopAnimation() {
      this.isRunning = false;
      if (this.animationId) {
        cancelAnimationFrame(this.animationId);
        this.animationId = null;
      }
    },
    
    // 鼠标移动处理
    handleMouseMove(event) {
      if (event.touches) {
        this.mouse.x = event.touches[0].pageX;
        this.mouse.y = event.touches[0].pageY;
      } else {
        this.mouse.x = event.clientX;
        this.mouse.y = event.clientY;
      }
      event.preventDefault();
    },
    
    // 触摸开始处理
    handleTouchStart(event) {
      if (event.touches.length == 1) {
        this.mouse.x = event.touches[0].pageX;
        this.mouse.y = event.touches[0].pageY;
      }
    },
    
    // 首次交互处理
    handleFirstInteraction(event) {
      if (this.hasFirstInteraction) return;
      
      this.hasFirstInteraction = true;
      document.removeEventListener("mousemove", this.handleFirstInteraction);
      document.removeEventListener("touchstart", this.handleFirstInteraction);
      
      document.addEventListener("mousemove", this.handleMouseMove);
      document.addEventListener("touchmove", this.handleMouseMove);
      document.addEventListener("touchstart", this.handleTouchStart);
      
      this.handleMouseMove(event);
      this.setupTentacles();
      this.animate();
    },
    
    // 设置事件监听器
    setupEventListeners() {
      document.addEventListener("mousemove", this.handleFirstInteraction);
      document.addEventListener("touchstart", this.handleFirstInteraction);
      document.body.addEventListener("orientationchange", this.resizeCanvas);
      window.addEventListener("resize", this.resizeCanvas);
      window.addEventListener("focus", this.startAnimation);
      window.addEventListener("blur", this.stopAnimation);
    },
    
    // 移除事件监听器
    removeEventListeners() {
      document.removeEventListener("mousemove", this.handleFirstInteraction);
      document.removeEventListener("touchstart", this.handleFirstInteraction);
      document.removeEventListener("mousemove", this.handleMouseMove);
      document.removeEventListener("touchmove", this.handleMouseMove);
      document.removeEventListener("touchstart", this.handleTouchStart);
      document.body.removeEventListener("orientationchange", this.resizeCanvas);
      window.removeEventListener("resize", this.resizeCanvas);
      window.removeEventListener("focus", this.startAnimation);
      window.removeEventListener("blur", this.stopAnimation);
    }
  }
};
</script>

<style scoped>
.canvas-bg {
  background-color: rgba(8,5,16,1);
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;
  pointer-events: none;
}
</style>